package web.servlet.logincheckcode.web;

import web.servlet.logincheckcode.dao.UserDao;
import web.servlet.logincheckcode.dao.UserDaoImpl;
import web.servlet.logincheckcode.domin.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author Administrator
 * @Date 2020/6/4 16:38
 **/
@WebServlet("/login")
public class Login extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*设置请求编码
         * 获取请求参数
         * 比较验证码
         * */
        request.setCharacterEncoding("utf-8");
        String code = request.getParameter("checkcode");
        HttpSession session = request.getSession();
        String session_code = (String) session.getAttribute("session_code");
        if (code.equalsIgnoreCase(session_code)) {
            System.out.println("验证码一致，接下来比较用户名");
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            UserDao dao = new UserDaoImpl();
            User user = dao.login(username, password);
            if (user==null) {
                /*用户名错误*/
                request.setAttribute("error_login", "用户名或密码");
                request.getRequestDispatcher("/verification code/logincheckcode.jsp").forward(request,response);
            }else {/*正确*/
                request.getSession().setAttribute("username",user);
                String path = request.getContextPath();
                response.sendRedirect(path+"/verification code/user.jsp");
            }
        } else {
            /**验证码不一致*/
            request.setAttribute("error_login", "验证码错误");
            request.getRequestDispatcher("/verification code/logincheckcode.jsp").forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
